
// @jhao 包含随机种子的随机函数
export default class RandomUtil {

    public static seed: number = 0

    private static getRandomSeed() {
        let seed: number = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
        // Logger.log("getRandomSeed=", seed, Number.MAX_SAFE_INTEGER)
        return seed
    }

    public static seedRandom(min: number = 0, max: number = 1) {
        this.seed = (this.seed * 9301 + 49297) % 233280;
        let rnd: number = this.seed / 233280.0;
        let result = min + rnd * (max - min);
        // Logger.log("seedRandom=", result)
        return result;
    }

    /** 随机minNum到maxNum的数字 （包含maxNum） */
    public static nextInt(minNum: number, maxNum: number, seed: number = RandomUtil.getRandomSeed()) {
        this.seed = seed
        return Math.floor(this.seedRandom() * (maxNum - minNum + 1) + minNum);
    }

    public static nextNumber(minNum: number, maxNum: number, seed: number = RandomUtil.getRandomSeed()) {
        this.seed = seed
        return this.seedRandom() * (maxNum - minNum) + minNum;
    }

    public static nextSign(seed: number = RandomUtil.getRandomSeed()) {
        if (this.nextBoolean(seed)) {
            return 1

        }
        return -1;
    }

    public static nextBoolean(seed: number = RandomUtil.getRandomSeed()) {
        this.seed = seed
        let temp = this.nextInt(0, 1, seed)
        if (temp = 0) {
            return true
        }
        return false;
    }

    public static randomArr(nowArr: Array<any>, needNum: number, seed: number = RandomUtil.getRandomSeed()): Array<any> {
        let tempArr: Array<any> = nowArr.concat();
        let resultArr: Array<any> = [];
        for (let index = 0; index < needNum; index++) {
            if (tempArr.length <= 0) {
                break;
            }
            let randomIndex: number = RandomUtil.nextInt(0, tempArr.length - 1, seed);
            resultArr.push(tempArr.splice(randomIndex, 1)[0]);
        }
        return resultArr;
    }

    public static randomItem(nowArr: Array<any>, seed: number = RandomUtil.getRandomSeed()) {
        return this.randomArr(nowArr, 1, seed)[0];
    }


    public static randomIndexByPercent(rateList: Array<number> = [100, 100, 100], seed: number = RandomUtil.getRandomSeed()) {
        let tempList: Array<number> = [];
        let totalTemp: number = 0;
        for (let i = 0; i < rateList.length; i++) {
            totalTemp += rateList[i];
            tempList[i] = totalTemp;
        }
        let randomTemp: number = this.nextInt(0, totalTemp, seed);
        let resultIndex: number = tempList.length - 1;
        for (let i = 0; i < tempList.length; i++) {
            if (randomTemp <= tempList[i]) {
                resultIndex = i;
                break;
            }
        }
        return resultIndex;
    }



}
